package com.xo.mall.configuration;

import com.xo.common.enums.TimeFormatEnum;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.Schema;
import org.springframework.format.FormatterRegistry;
import org.springframework.format.datetime.DateFormatter;
import org.springframework.format.datetime.standard.DateTimeFormatterRegistrar;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.time.format.DateTimeFormatter;

@Schema(description = "全局MVC配置")
public class GlobalMvcConfiguration implements WebMvcConfigurer {

    @Override
    @Operation(summary = "全局时间格式化")
    public void addFormatters(FormatterRegistry registry) {
        DateTimeFormatterRegistrar dateTimeFormatterRegistrar = new DateTimeFormatterRegistrar();
        dateTimeFormatterRegistrar.setDateTimeFormatter(DateTimeFormatter.ofPattern(TimeFormatEnum.LOCAL_DATE_TIME.getCode()));
        dateTimeFormatterRegistrar.setDateFormatter(DateTimeFormatter.ofPattern(TimeFormatEnum.LOCAL_DATE.getCode()));
        dateTimeFormatterRegistrar.setTimeFormatter(DateTimeFormatter.ofPattern(TimeFormatEnum.LOCAL_TIME.getCode()));
        dateTimeFormatterRegistrar.registerFormatters(registry);

        registry.addFormatter(new DateFormatter(TimeFormatEnum.DATE.getCode()));
    }

    /**
     * 配置跨域资源共享
     */
    @Override
    @Operation(summary = "配置跨域资源共享")
    public void addCorsMappings(CorsRegistry registry) {
        // 允许跨域访问的路径模式，/**表示所有路径
        registry.addMapping("/**")
                // 允许的来源，*表示允许所有域名，生产环境建议指定具体域名
                .allowedOriginPatterns("*")
                // 允许的请求方法
                .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
                // 允许的请求头
                .allowedHeaders("*")
                // 是否允许携带cookie
                .allowCredentials(true)
                // 预检请求的缓存时间（秒），减少预检请求次数
                .maxAge(3600);
    }
}
